package com.sharding.jdbc.demo.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sharding.jdbc.demo.mapper.UserMapper;
import com.sharding.jdbc.demo.model.User;
import com.sharding.jdbc.demo.service.UserService;
//import com.sharding.jdbc.demo.util.sequence.Sequence;
import lombok.extern.slf4j.Slf4j;

/**
* @comments
* @author  zg
* @date 2018年12月2日
*/
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 使用shardingSphere自带的雪花算法（配置见application.yml）生成用id
	 * @return
	 */
	@RequestMapping("/add")
	public String addUser() {
		//Sequence sequence = new Sequence(0);
		//long userId = sequence.nextId();
		User user = new User();
		//随机一个年龄
		int age = (int) (Math.random() * 100);
		//user.setId(userId);
		user.setAge(age);
		//user.setCrtTime(crtTime);
		user.setName("");
		int count = userMapper.insert(user);
		if(count > 0) {
			Long userId = user.getId();
			long mod = userId % 3;
			return "Success create user, id is " + userId + ", Mod is " + mod;
		}
		return "Failure!";
	}
	
	/**
	 * 查询所有（数据合集，会把几张表的数据都查询出来）
	 * @return
	 */
	@RequestMapping("/list-all")
	public Object listAll() {
		
		List<User> list = userMapper.selectAll();
		
		return list;
	}
	
	@RequestMapping("/select-age")
	public Object criteriaQuery(@RequestParam(name = "ageMin", defaultValue = "0") Integer ageMin,
			@RequestParam(name = "ageMax", defaultValue = "100") Integer ageMax) {
		
		List<User> list = userMapper.selectByAge(ageMin, ageMax);
		
		return list;
	}
	
	/**
	 * 分页查询
	 * @author zg
	 * @date 2020年4月15日 
	 * @param user
	 * @return
	 */
	@RequestMapping("/list")
	public Object list(@RequestParam(name = "page", defaultValue = "1") Integer page) {
		
		List<User> list = null;
		try {
			list = userService.queryList(page);
		} catch (Exception e) {
			log.error("", e);
		}
		
		return list;
	}
	
	
}
